"""
Copyright 2012 Wieser Dietmar, Margit Mutschlechner.

This file is part of Multimedia Social Networking Platform.

Multimedia Social Networking Platform is free software: 
you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Multimedia Social Networking Platform is distributed
in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Multimedia Social Networking Platform.  
If not, see <http://www.gnu.org/licenses/>.

"""

import MySQLdb
import traceback
from msnp.logger import Logger
from msnp.persistence.mysql import PlayerDBController

def __openConnection(host, username, password):
    """Opens a connection to the ptp database with the global arguments.
    
    Args:
        host: A String representing the host name of the database.
        username: A String representing the user name.
        password: A String representing the password of the user.
    
    Returns:
        Returns a tuple of (Connection, Cursor) or the tuple (None, None) if no connection could be set up.
    """
    database = MySQLdb.connect(host, username, password, charset="utf8", use_unicode=True)
    if database != None:
        cursor = database.cursor()
        return (database, cursor)
    return (None, None)

def __closeConnection(database):
    """Close the connection to the database given as an argument.
    
    Args:
        database: The Connection object representing the database where the connection should be closed.
    """
    if database != None:
        database.close()

def testDBCredentials(host, username, password):
    """Tests whether the database with the given credentials is accessible or not.
    
    Args:
        host: A String representing the host name of the database.
        username: A String representing the user name.
        password: A String representing the password of the user.
    
    Returns:
        True is returned if the database is accessible, False if an exception occurred while connecting.
    """
    try:
        (database, cursor) = __openConnection(host, username, password)
        if database != None and cursor != None:
            __closeConnection(database)
            Logger.info('db validation ok')
            return True
    except:
        Logger.info('db validation failed')
        Logger.info(traceback.format_exc())
    return False

def testPlayerDBCredentials(playerDBSettings):
    """Tests whether the player database with the given credentials is accessible or not.
    
    Tries to connect to the player database
    and checks whether the schema and required tables exist.
    
    Args:
        playerDBSettings: A DatabaseSettings object containing the connection information.
    
    Returns:
        True is returned if the player database is accessible, False if an error occurred while connecting.
    """
    try:
        player = playerDBSettings.getPlayer()
        host = playerDBSettings.getHost()
        username = playerDBSettings.getUser()
        password = playerDBSettings.getPassword()
        schema = playerDBSettings.getSchema()
        (database, cursor) = __openConnection(host, username, password)
        if database != None and cursor != None:
            if PlayerDBController.existsSchemaAndTables(database, cursor, schema, player):
                __closeConnection(database)
                Logger.info('db validation ok')
                return True
            Logger.info('db validation failed (schema is not ok)')
    except:
        Logger.info('db validation failed')
        Logger.info(traceback.format_exc())
    return False
